package com.itheima.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author ：hg
 * @date ：Created in 2021/12/23 20:24
 * @description：权限控制
 */
@Component   //交给spring进行管理
public class SpringSecurityUserService implements UserDetailsService {

    @Reference //通过dubbo通过网络远程调用服务提供方来获取数据库中的用户信息
    private UserService userService;

    //根据用户名查询用  户信息
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //调用服务
        User user = userService.findByUsername(username);
        //判断是否存在用户
        if (null == user) {
            //用户不存在
            return null;
        }

        List<GrantedAuthority> list = new ArrayList<>();

        //动态为当前用户进行授权
        Set<Role> roles = user.getRoles();
        roles.forEach(role->{
            //遍历角色集合，为用户进行授予角色
            list.add(new SimpleGrantedAuthority(role.getKeyword()));
            Set<Permission> permissions = role.getPermissions();
            //遍历权限集合，为用户进行授权
            permissions.forEach(permission -> {
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            });
        });

        return new org.springframework.security.core.userdetails.User(username,user.getPassword(),list);
    }
}
















